<template>
  <div class="student" style="margin-top: 50px;">
    <h2 style="font-weight: bold;">学生管理系统</h2>

    <!-- 学生列表 -->
    <el-table :data="students" style="width: 800px;"
              border
              :header-cell-style="{
                  background: '#DAF8D4',
                  color: '#333333',
                  fontWeight: 'bold',
                  fontSize: '20px',
              }">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column label="年级" prop="grade"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template v-slot="scope">
          <div class="button-group">
            <!-- 编辑按钮 -->
            <el-button type="primary" size="medium" @click="editStudent(scope.row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="medium" @click="deleteStudent(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增按钮 -->
    <el-button type="success"
               style="margin-top: 20px;"
               @click="addStudent()">新增</el-button>

    <!-- 编辑/添加学生信息的对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑学生信息">
      <el-form :model="currentStudent" ref="studentForm" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="currentStudent.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="currentStudent.age"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="currentStudent.grade"></el-input>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStudent">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'StudentView',
  data() {
    return {
      // 学生列表数据
      students: [], // 初始为空数组
      // 当前编辑/添加的学生信息
      currentStudent: { id: 0, name: '', age: '', grade: '' },
      // 是否显示编辑/添加对话框
      dialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /^\d+$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error('年龄必须为数字值'));
              }
            },
            trigger: 'blur'
          }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getStudents(); // 在组件创建时获取学生数据
  },
  methods: {
    // 异步获取学生数据
    async getStudents(){
      try {
        let params = {
          pageNumber: 1,
          pageSize: 10
        };
        const response = await this.$http.post('student/getStudents',params);
        console.log(response)
        this.students = response.data.data; // 假设返回的数据格式为数组
      } catch (error) {
        console.error('Error fetching students:', error);
      }
    },
    // 添加学生
    addStudent() {
      this.currentStudent = { id: 0, name: '', age: '', grade: '' };
      this.dialogVisible = true;
    },
    // 编辑学生
    editStudent(student) {
      this.currentStudent = Object.assign({}, student);
      this.dialogVisible = true;
    },
    // 保存学生信息
    saveStudent() {
      // 表单验证
      this.$refs.studentForm.validate(valid => {
        if (valid) {
          // 新增或更新学生信息
          this.$http.post('student/saveStudent', this.currentStudent)
              .then(() => {
                // 处理成功响应
                this.getStudents(); // 重新请求查询接口
                this.dialogVisible = false;
              })
              .catch(error => {
                // 处理错误响应
                console.error('Error saving student:', error);
              });
        }
      });
    },
    // 删除学生
    deleteStudent(id) {
      this.$confirm('确认删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端接口删除学生
        this.$http.get(`student/deleteStudent?id=${id}`)
            .then(() => {
              // 处理成功响应
              this.getStudents(); // 重新请求查询接口
              this.$message.success('删除成功');
            })
            .catch(error => {
              console.error('删除学生失败', error);
              this.$message.error('删除学生失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
};
</script>

<style>

.button-group {
  display: flex;
  justify-content: space-between;
}


.student {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-table .cell {
  text-align: center;
}

</style>
